<?php
declare(strict_types=1);

namespace app\controller\user;

use app\BaseController;
use app\model\UserAddress;
use think\facade\{Db, Log};
use think\Request;

class AddressController extends BaseController
{
    /**
     * 获取地址列表
     */
    public function list(Request $request)
    {
        $type = $request->param('type', 'all');
        $where = [
            'user_id' => $request->userId,
            'merchant_id' => $request->merchantId
        ];
        
        if ($type !== 'all') {
            $where['address_type'] = $type === 'sender' ? 1 : 2;
        }
        
        $list = UserAddress::where($where)
            ->order('id', 'desc')
            ->select();
            
        return $this->success('获取成功', $list);
    }
    
    /**
     * 添加地址
     */
    public function create(Request $request)
    {
        $data = $this->validate($request->post(), [
            'address_type' => 'require|in:1,2',
            'province' => 'require|max:20',
            'city' => 'require|max:20',
            'county' => 'require|max:20',
            'address' => 'require|max:100',
            'username' => 'require|max:20',
            'phone' => 'require|mobile'
        ]);
        
        try {
            $data['user_id'] = $request->userId;
            $data['merchant_id'] = $request->merchantId;
            $data['create_time'] = date('Y-m-d H:i:s');
            
            $address = UserAddress::create($data);
            
            return $this->success('添加成功', $address);
        } catch (\Exception $e) {
            Log::error('添加地址失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 更新地址
     */
    public function update(Request $request, $id)
    {
        $data = $this->validate($request->post(), [
            'address_type' => 'require|in:1,2',
            'province' => 'require|max:20',
            'city' => 'require|max:20',
            'county' => 'require|max:20',
            'address' => 'require|max:100',
            'username' => 'require|max:20',
            'phone' => 'require|mobile'
        ]);
        
        try {
            $address = UserAddress::where([
                'id' => $id,
                'user_id' => $request->userId,
                'merchant_id' => $request->merchantId
            ])->find();
            
            if (!$address) {
                throw new \Exception('地址不存在');
            }
            
            $data['update_time'] = date('Y-m-d H:i:s');
            $address->save($data);
            
            return $this->success('更新成功', $address);
        } catch (\Exception $e) {
            Log::error('更新地址失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 删除地址
     */
    public function delete(Request $request, $id)
    {
        try {
            $result = UserAddress::where([
                'id' => $id,
                'user_id' => $request->userId,
                'merchant_id' => $request->merchantId
            ])->delete();
            
            if (!$result) {
                throw new \Exception('地址不存在');
            }
            
            return $this->success('删除成功');
        } catch (\Exception $e) {
            Log::error('删除地址失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 设为默认地址
     */
    public function setDefault(Request $request, $id)
    {
        Db::startTrans();
        try {
            $address = UserAddress::where([
                'id' => $id,
                'user_id' => $request->userId,
                'merchant_id' => $request->merchantId
            ])->find();
            
            if (!$address) {
                throw new \Exception('地址不存在');
            }
            
            // 取消原默认地址
            UserAddress::where([
                'user_id' => $request->userId,
                'merchant_id' => $request->merchantId,
                'address_type' => $address->address_type,
                'is_default' => 1
            ])->update(['is_default' => 0]);
            
            // 设置新默认地址
            $address->save(['is_default' => 1]);
            
            Db::commit();
            return $this->success('设置成功');
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('设置默认地址失败: ' . $e->getMessage());
            return $this->error($e->getMessage());
        }
    }
} 